import {Component, ElementRef} from '@angular/core';
import {
  IonicPage,
  NavController,
  ToastController,
  NavParams,
  Keyboard,
  AlertController,
  LoadingController
} from 'ionic-angular';
import {UnloadApi} from '../../api/unload/UnloadApi';
import {ProjectPlanApi} from '../../api/project/ProjectPlanApi';
import {BarcodeScanner } from '@ionic-native/barcode-scanner';

@IonicPage()
@Component({
  selector: 'unload-container',
  templateUrl: 'unload-container.html'
})
export class UnloadContainer {
  private planPositionId: string;
  private projectId: string;
  private planId: string;
  private qrcode: string;
  private unloadbtnTag: boolean=true;
  private container: any;
  private containerId: string;
  private LeaveTag: boolean = true;


  //  离开页面守卫
  ionViewCanLeave(): boolean {
    return this.LeaveTag;
  }

  constructor(private barcodeScanner:BarcodeScanner,public planApi: ProjectPlanApi, private loadingCtrl: LoadingController, private alertCtrl: AlertController, private navParams: NavParams, private UnloadApi: UnloadApi, private toastCtrl: ToastController, private navCtrl: NavController, private ele: ElementRef, private keyboard: Keyboard) {
    this.container = {
      containerID: "",
      containerName: "",
      containerCode: "",
      containerType: "",
      containerLong: "",
      containerWide: "",
      containerHigh: "",
      containerDeadWeight: "",
      containerBearWeight: "",
      containerPermission: "",
      containerComment: ""
    };
    this.planPositionId = navParams.get("planPositionId");
    this.projectId = navParams.get("projectId");
    this.planId = navParams.get("planId");
  }

  //输入框值改变事件
  infoChange(Qrcode) {
    const http$ = this.UnloadApi.ScanContainer(Qrcode, this.planPositionId, this.planId);
    http$.subscribe((res: any) => {
     // this.keyboard.close();
      if (res.state) {
        for (let i = 0; i < this.ele.nativeElement.querySelectorAll(".hides").length; i++) {
          this.ele.nativeElement.querySelectorAll(".hides")[i].removeAttribute("hidden");
          this.ele.nativeElement.querySelector("#scanContainerBtn").click();
        }
        this.unloadbtnTag = false;
        this.container = res;
        this.containerId = res.containerID;
      } else {
        this.ele.nativeElement.querySelector("#scanContainerBtn").click();
        this.showMsg(res.msg);
      }
    });
  }


  toScan() {
    this.barcodeScanner.scan({showTorchButton:true,resultDisplayDuration:0}).then((data) => {
      if (data.text.length!=0){
        const http$ = this.UnloadApi.ScanContainer(data.text, this.planPositionId, this.planId);
        http$.subscribe((res: any) => {
          // this.keyboard.close();
          if (res.state) {
            for (let i = 0; i < this.ele.nativeElement.querySelectorAll(".hides").length; i++) {
              this.ele.nativeElement.querySelectorAll(".hides")[i].removeAttribute("hidden");
            //  this.ele.nativeElement.querySelector("#scanContainerBtn").click();
            }
            this.unloadbtnTag = false;
            this.container = res;
            this.containerId = res.containerID;
          } else {
           // this.ele.nativeElement.querySelector("#scanContainerBtn").click();
            this.showMsg(res.msg);
          }
        });
      }else{
        this.fixshowMsg("请扫描正确的二维码!");
      }
    }, (err)=> {
      this.showMsg("扫描出现异常" + err);
    });
  }

  /*choseContainer() {
    const http$ = this.UnloadApi.ChoseContainers();
    http$.subscribe((res: any) => {
      let alert = this.alertCtrl.create();
      alert.setTitle('请选择一个容器');
      for (var index in res.data) {
        let item: any = res.data[index];
        alert.addInput({
          type: 'radio',
          label: '名称:' + item.containerName + ' 编码:' + item.containerCode,
          value: item
        });
      }
      alert.addButton('取消');
      alert.addButton({
        text: '确定',
        handler: data => {
          for (let i = 0; i < this.ele.nativeElement.querySelectorAll(".hides").length; i++) {
            this.ele.nativeElement.querySelectorAll(".hides")[i].removeAttribute("hidden");
          }
          this.unloadbtnTag = false;
          let type = "未定义容器";
          if (data.containerType == 0) {
            type = "仓储容器";
          }
          else if (data.containerType == 1) {
            type = "运输容器";
          }
          this.container = {
            containerID: data.id,
            containerName: data.containerName,
            containerCode: data.containerCode,
            containerType: type,
            containerLong: data.longs,
            containerWide: data.wide,
            containerHigh: data.high,
            containerDeadWeight: data.deadWeight,
            containerBearWeight: data.bearWeight,
            containerPermission: data.permission,
            containerComment: data.comment
          };
          this.containerId = data.id;
        }
      });
      alert.present();
    });

  }*/

  scan() {
    this.ele.nativeElement.querySelector("#scancontainer").focus();
  }

  goScanMateriel() {
    this.navCtrl.push("UnloadMateriel", {
      "planId": this.planId,
      "planPositionId": this.planPositionId,
      "projectId": this.projectId,
      "containerId": this.containerId
    });
  }

  UnloadMaterielAll() {
    let confirm = this.alertCtrl.create({
      title: '是否使用一键卸货?',
      message: '一键卸货会将此容器中所有货物全部卸至即将扫描的目标容器',
      buttons: [
        {
          text: '取消',
          handler: () => {
          }
        },
        {
          text: '确认',
          handler: () => {
            let loader = this.loadingCtrl.create({
              content: "请等待...",
            });
            loader.present();
            const http$ = this.UnloadApi.UnloadMaterielAll(this.planId, this.containerId, this.planPositionId);
            http$.subscribe((res: any) => {
              if (res.state) {
                this.unloadbtnTag = true;
                loader.dismiss();
                this.showMsg(res.msg);
              } else if (res.repeat) {
                loader.dismiss();
                this.showMsg(res.msg);
              }
              else {
                loader.dismiss();
                this.showMsg("一键卸货失败请检查网络并重新登录再试!");
              }
            });
          }
        }
      ]
    });
    confirm.present();

  }

  //点击取消返回
  goBack() {
  //this.ele.nativeElement.querySelector("[ng-reflect-klass='back-button']").click();
  this.navCtrl.pop();
  }

  showMsg(msg: string) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }

  fixshowMsg(msg: string) {
    this.LeaveTag = false;
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
    setTimeout(() => this.LeaveTag = true, 1000);
  }


}
